package com.demo.gateway.mapping;

/**
 * @author yzy
 * @date 2024/7/15 下午11:18
 */

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;


public class JsonTraversalExample {


    public static void main(String[] args) throws IOException {
        String s = "D:\\MyData\\yanzy59\\IdeaProjects\\gateway2\\src\\main\\resources\\conf\\channel\\demo\\mapping.json";

        String json = FileUtils.readFileToString(new File(s));
        // 创建 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();

        // 解析 JSON 字符串为 JsonNode
        JsonNode rootNode = objectMapper.readTree(json);

        // 调用递归遍历方法
        traverseJson("", rootNode);
    }

    public static void readJsonToTree(String json){
        try {
            // 创建 ObjectMapper 对象
            ObjectMapper objectMapper = new ObjectMapper();

            // 解析 JSON 字符串为 JsonNode
            JsonNode rootNode = objectMapper.readTree(json);

            // 调用递归遍历方法
            traverseJson("", rootNode);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    // 递归遍历 JsonNode 方法
    public static void traverseJson(String prefix, JsonNode node) {
        if (node.isObject()) {
            node.fields().forEachRemaining(entry -> {
                traverseJson(prefix + "." + entry.getKey(), entry.getValue());
            });
        } else if (node.isArray()) {
            for (int i = 0; i < node.size(); i++) {
                traverseJson(prefix, node.get(i));
            }
        } else {
            System.out.println(prefix.substring(1) + " = " + node.asText());
        }
    }
}
